<?php



namespace app\client\model;



use app\client\model\ShopSpecAttr as ShopSpecAttrModel;

use app\client\model\ShopGoodsType as ShopGoodsTypeModel;

use app\client\model\Shop as ShopModel;

use think\Request;

use think\Model;

use think\Session;

use think\Db;
use app\client\model\ShopGoodsSpec as ShopGoodsSpecModel;
class ShopGoods extends Model

{



    // 审核状态

    protected function getStatusTextAttr($value, $data)

    {

        $status = [1 => '审核成功', 2 => '等待审核', 3 => '违规下架'];

        return $status[$data['status']];

    }

    protected function getDcTextAttr($value, $data)
    {

        $status = [1 => '借方', 2 => '贷方'];
        return $status[$data['dc']];
    }



    // 栏目名称

    protected function getShopParenTextAttr($value, $data)

    {

        $ShopParenText = ShopGoodsTypeModel::where(['id' => $data['parenTid']])->value('title');



        return $ShopParenText;

    }

    protected function getGoodsTypeAttr($value,$data){

        return Db::name('goods_type')->where('id',$data['goods_id'])->value('title');
    }

    public function getAudingTextAttr($value, $data)
    {
        $status = [1 => '等待审核', 2 => '审核成功', 3 => '审核失败'];
        return $status[$data['auding_status']];
    }
//
    public function getAudingManageAttr($value, $data)
    {
        $ret = Db::name('manager')->where('id',$data['auding_id'])->value('username');
        return $ret;
    }
    public function getCreateManageAttr($value, $data)
    {
        $ret = Db::name('manager')->where('id',$data['create_id'])->value('username');
        return $ret;
    }

    public function getInventorySumAttr($value, $data)
    {
        $ret = Db::name('shop_spec_attr')->where('goods_id',$data['id'])->where('shop_id',0)->sum('inventory');
        return $ret;
    }


    // 模型事件

    protected static function init()

    {

       //halt('我在调试,您先别操作');
        // 写入前

        self::event('before_insert',function ($data){

            $data->activity = 2;
            $data->create_time = date('Y-m-d H:i:s',time());

        });

        self::event('before_write', function ($data) {
//            $spec = Request::instance()->param('spec/a');
            // 创建时间
//            foreach ($spec as $key => $value) {
//                dump(implode(',',$value['sp_value']));
//            }
//            halt($spec);
            $data->date_time = date('m月d日', strtotime(Request::instance()->param('create_time')));  // 创建时间（时间格式）

            $data->rebate_percentage = 0;               // 创建时间

            $data->picUrl = uploadImg();                                                             // 图片

            $data->thumb_img = show_thumb_pic($data->picUrl);                                         // 缩略图

            $data->picArr = serialize(Request::instance()->param('picArr/a'));// 组图



            $data->goods_attr = serialize(Request::instance()->param('sp_val/a'));                   // 属性规格



            $data->goods_title = str_replace(' ', '', Request::instance()->param('goods_title'));    // 编辑标题方法

            $data->goods_str = parentStr(Request::instance()->param('goods_id'), 'goods_type');      // parenStr方法(平台)

            $data->parentStr = parentStr(Request::instance()->param('parenTid'), 'shop_goods_type'); // parenStr方法
            $data->update_time = date('Y-m-d H:i:s',time());


            $data->pic_url = uploadImg('pic_url');
            auding($data);



        });







        // 写入后

        self::event('after_write', function ($data) {

            $spec = Request::instance()->param('spec/a');

            $id = Request::instance()->param('id');


            //$goods_id = Request::instance()->param('goods_id');
            //$attr = ShopGoodsSpecModel::where('goods_type_id' ,['like', '%,' . $goods_id . ',%'],['eq',''],'or')->fetchSql(false)->where('auding_status',2)->where('is_delete',1)->select()->toArray();

                if (!empty($spec)) {

                    // 先清空sku关联表
                    //20190416屏蔽
//
                    if (empty($id)) { //添加
                        //id不为空是添加;
                        // ShopSpecAttrModel::destroy(['goods_id' => $id]);

                        $id = $data->id;
                        //  if(empty($attr)) {

                        // Db::name('shop_spec_attr')->insert(['goods_id' => $id,'shop_id' => 0, 'attribute' => '无','inventory' => Request::instance()->param('inventory')]);
                        // }

                    }else{
                       // ShopSpecAttrModel::destroy(['goods_id' => $id]); //存在sku
                        //halt(1);'goods_id' => $id,'shop_id' => 0, 'attribute' => '无',
                        //id不为空是修改;
                        //if(empty($attr)) {
                       // Db::name('shop_spec_attr')->where(['goods_id' => $id,'shop_id' =>0,'attribute' => '无'])->update(['inventory' => Request::instance()->param('inventory')]);
                        //}else{
                       // ShopSpecAttrModel::destroy(['goods_id' => $id]); //存在sku
                        // }



                        //(new ShopSpecAttr())->where(['goods_id' => $id])->delete();
                    }


                    $information = '';

                    // 添加sku关联表

                    foreach ($spec as $key => $value) {



                        if (empty($value['id'])) {

                            $information = [

                                'goods_id'       => $id,
                                'price'       => $value['price'],
                                'attribute_id'   => $key,

                                'attribute'      => implode(',', $value['sp_value']),

                                'attr'           => serialize($value['sp_value']),

//                                'inventory'      => $value['stock'],

                            ];



                        } else {



                            $information = [
                                'price'       => $value['price'],
                                'goods_id'       => $id,

                                'attribute_id'   => $key,

                                'attribute'      => implode(',', $value['sp_value']),

                                'attr'           => serialize($value['sp_value']),

//                                'inventory'      => $value['stock'],





                            ];



                        }

                      $new_shop_spec_attr = Db::name('shop_spec_attr')->where('goods_id',$data->id)->where('attribute',implode(',',$value['sp_value']))->find();
                      if(!empty($new_shop_spec_attr)){
                          Db::name('shop_spec_attr')->where('goods_id',$data->id)->where('attribute',implode(',',$value['sp_value']))->update($information);
                      }else{
                          Db::name('shop_spec_attr')->insert($information);
                      }


                    }



                   // (new ShopSpecAttrModel())->saveAll($information);

                }else{ //没有属性
                    $find = Db::name('shop_spec_attr')->where(['goods_id' => $data->id,'shop_id' =>0,'attribute' => '无','price' => Request::instance()->param('price')])->find();
                    if(empty($find)){
                        Db::name('shop_spec_attr')->insert(['goods_id' => $data->id,'shop_id' => 0, 'attribute' => '无','inventory' => Request::instance()->param('inventory','0'),'price' => Request::instance()->param('price')]);
                    }else{
                        Db::name('shop_spec_attr')->where(['goods_id' => $data->id,'shop_id' =>0,'attribute' => '无'])->update(['inventory' => Request::instance()->param('inventory','0'),'price' => Request::instance()->param('price')]);
                    }

                }


        });

    }



    public function shopSpecAttr()

    {

        return $this->hasMany('ShopSpecAttr', 'goods_id', 'id');

    }



    public function flagAttr()

    {

        return $this->hasMany('ShopGoodsFlag', 'goods_id', 'id');

    }

    public function getAudingText1Attr($value, $data)
    {
        $status = [1 => '等待审核', 2 => '审核成功', 3 => '审核失败'];
        return $status[$data['auding_status1']];
    }
    public function getAudingText2Attr($value, $data)
    {
        $status = [1 => '等待审核', 2 => '审核成功', 3 => '审核失败'];
        return $status[$data['auding_status2']];
    }
    public function getAudingText3Attr($value, $data)
    {
        $status = [1 => '等待审核', 2 => '审核成功', 3 => '审核失败'];
        return $status[$data['auding_status3']];
    }


//


}

